let ws;
const ws_url = "ws://localhost:8080/poj-java/chat";
let isConnected = false;
let Ausername = $(".username").val(); // 发送人
let myAvatar = $(".myAvatar").attr('src'); // 发送人头像

// 存储当前选中的接收人信息（全局变量）
let currentRecipient = {
    username: '',
    avatar: ''
};

$(function() {
    // 初始化WebSocket（先不连接，等用户选择接收人后再连接）
    // ws_connect();
    
    $("#send-message").click(function() {
        ws_sendMsg();
    });
    
    // 加载聊天用户列表
    loadChatUsers();
});

// 加载聊天用户列表
function loadChatUsers() {
    let sendUsername = $(".username").val();
    console.log("当前用户:", sendUsername);
    
    $.ajax({
        url: "getChaertingUsers.do",
        type: "GET",
        data: {
            sendUsername: sendUsername
        },
        success: function(data) {
            console.log("聊天用户数据:", data);
            let fatherDiv = $(".chat-list");
            fatherDiv.empty(); // 清空现有内容
            
            for (var i = 0; i < data.data.length; i++) {
                let user = data.data[i];
                let myChartingDiv = `
                    <div class="chat-item d-flex p-3 border-bottom cursor-pointer" 
                         data-user-id="${user.userid}" 
                         data-username="${user.username}" 
                         data-avatar="${user.headimg}">
                        <div class="user-avatar mr-3">
                            <img src="${user.headimg}" alt="用户头像" class="rounded-circle" width="48">
                        </div>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="mb-1">${user.username}</h6>
                                <small class="text-muted"></small>
                            </div>
                        </div>
                    </div>
                `;
                fatherDiv.append(myChartingDiv);
            }
            
            // 添加点击事件处理
            addChatItemClickHandlers();
        }
    });
}

// 添加聊天项点击事件处理
function addChatItemClickHandlers() {
    $('.chat-list').off('click', '.chat-item'); // 移除旧的事件绑定
    $('.chat-list').on('click', '.chat-item', function() {
        // 获取点击的用户数据
        const username = $(this).data('username');
        const avatar = $(this).data('avatar');
        console.log("选中用户:", username, "头像:", avatar);
        
        //更新当前接收人信息
        currentRecipient.username = username;
        currentRecipient.avatar = avatar;
        
        //更新聊天窗口标题
        updateChatHeader(username, avatar);
        
        // 加载聊天记录
        selecOurmsg(Ausername, username);
        
        // 更新WebSocket连接（使用新的接收人）
        updateWebSocketConnection(username);
        
        //添加活动状态
        $('.chat-item').removeClass('active-chat');
        $(this).addClass('active-chat');
    });
}

// 更新聊天窗口标题
function updateChatHeader(username, avatar) {
    const chartingHead = ` `;
    $(".chat-header").html(chartingHead);
}

// 更新WebSocket连接
function updateWebSocketConnection(recipientUsername) {
    // 关闭旧连接（如果存在）
    if (ws && ws.readyState !== WebSocket.CLOSED) {
        ws.close();
        console.log('关闭旧WebSocket连接');
    }
    
    // 建立新连接
    ws_connect(recipientUsername);
}

// 修改WebSocket连接函数以接收recipientUsername参数
function ws_connect(recipientUsername) {
    if (!recipientUsername) {
        console.error('未指定接收人');
        return;
    }
    
    const fullUrl = `${ws_url}?sendUsername=${Ausername}&reciveusername=${recipientUsername}`;
    
    if ('WebSocket' in window) {
        ws = new WebSocket(fullUrl);
    } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket(fullUrl);
    } else {
        console.log('Error: WebSocket is not supported by this browser.');
        return;
    }

    ws.onopen = function() {
        console.log('WebSocket连接已建立:', fullUrl);
    };

    ws.onclose = function() {
        console.log('WebSocket连接已关闭');
    };
    
    ws.onmessage = function(message) {
        handleWebSocketMessage(message);
    };
}

// 处理WebSocket消息
function handleWebSocketMessage(message) {
    try {
        const messageData = JSON.parse(message.data);
        console.log("收到消息:", messageData);
        // 判断消息是否属于当前对话
        if (isMessageForCurrentChat(messageData)) {
            // 创建消息元素并添加到聊天窗口
            createMessageElement(messageData);
        }
        
        scrollToBottom();
    } catch (e) {
        console.error("解析消息错误:", e);
    }
}

// 判断消息是否属于当前对话
function isMessageForCurrentChat(messageData) {
    return (
        // 当前用户发送给当前接收人的消息
        (messageData.sendUsername === Ausername && 
         messageData.reciveusername === currentRecipient.username) ||
        
        // 当前接收人发送给当前用户的消息
        (messageData.sendUsername === currentRecipient.username && 
         messageData.reciveusername === Ausername)
    );
}

// 创建消息元素
function createMessageElement(messageData) {
    const isSender = messageData.sendUsername === Ausername;
    const messageClass = isSender ? 'message sent' : 'message received';
    
    const messageElement = `
        <div class="${messageClass}">
            <div class="message-content">
                ${!isSender ? `<div class="message-name">${messageData.sendUsername}</div>` : ''}
                <div class="message-bubble">${messageData.message}</div>
                <div class="message-time">${messageData.send_at}</div>
            </div>
        </div>
    `;
    
    $('.chat-messages').append(messageElement);
}

//发送消息函数
function ws_sendMsg() {
    if (!currentRecipient.username) {
        alert('请先选择聊天对象');
        return;
    }
    
    const msg = $("#message").val().trim();
    if (!msg) return;
    
    const data = {
        sendUsername: Ausername,
        reciveusername: currentRecipient.username,
        message: msg
    };
    
    console.log("发送消息:", JSON.stringify(data));
    
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify(data));
        $("#message").val("");
        
        scrollToBottom();
    } else {
        console.error('WebSocket未连接');
    }
};

// 滚动到底部
function scrollToBottom() {
    const chatMessages = $('.chat-messages')[0];
    if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 获取聊天记录
function selecOurmsg(sender, receiver) {
    $.ajax({
        url: "getChaertingRecords.do",
        type: "GET",
        data: {
            sendUsername: sender,
            reciveusername: receiver,
        },
        success: function(data) {
            console.log("聊天记录数据:", data);
            renderChatMessages(data.data || []);
        }
    });
}

// 渲染聊天记录
function renderChatMessages(messages) {
    const $chatMessages = $('.chat-messages');
    $chatMessages.empty();
    
    if (!messages || messages.length === 0) {
        $chatMessages.html('<div class="no-messages">没有聊天记录</div>');
        return;
    }
    
    messages.forEach(msg => {
        const isSender = msg.sendUsername === Ausername;
        const messageClass = isSender ? 'message sent' : 'message received';
        
        const messageHtml = `
            <div class="${messageClass}">    
                <div class="message-content">
                    ${!isSender ? `<div class="message-name">${msg.sendUsername}</div>` : ''}
                    <div class="message-bubble">${msg.message}</div>
                    <div class="message-time">${msg.send_at}</div>
                </div>
            </div>
        `;
        
        $chatMessages.append(messageHtml);
    });
    
    scrollToBottom();
}
$("#message").on("keypress", function(e) {
	  if (e.which === 13) { // Enter键
	      e.preventDefault();
	      ws_sendMsg();
	  }
});